import { Popup } from 'devextreme-react';
import React, { useImperativeHandle, useRef, useState } from 'react';
import { intl } from '../../../utils';
import { Form, Input, message } from 'antd';
import { queryDgmc, queryDgsyh, queryfjName } from './service';
import notify from 'devextreme/ui/notify';

const ErrorEditPupop = React.forwardRef((props: any, ref: any) => {
    const [visible, setVisible] = useState<boolean>(false);
    const popupRef = useRef<any>(null);
    const [formUseRef] = Form.useForm();
    const [openForm, setOpenForm] = useState<any>({
        itemName: false,
        itemSyh: false
    });

    const [formSyh, setFormSyh] = useState<any>({
        validateStatus: false,
        validateHelp: ''
    });


    const InputFunRef = useRef<any>();
    const InputObjRef = useRef<any>();


    // 自定义方法
    useImperativeHandle(ref, () => ({
        show: (tempObj: any, funTemp: any) => {
            setVisible(true);
            // console.log(tempObj, '@@@tempObj');
            InputObjRef.current = tempObj;
            InputFunRef.current = funTemp;
            formUseRef.setFieldsValue({
                fileName: tempObj.tempFileName,
                fileSyh: tempObj.tempFileSyh,
            });
            setOpenForm({
                itemName: tempObj.itemName,
                itemSyh: tempObj.itemSyh,
            })
        },
    }));


    // const res = await queryDgmc({
    //     dbname: diaParams.current?.args.dbname,
    //     dgnd: diaParams.current?.args.dgnd,
    //     dgmc: v
    // });
    // if (res.success) return notify('该底稿名称号重复', 'warning', 2000);

    // const res = await queryDgsyh({
    //     dbname: diaParams.current?.args.dbname,
    //     dgnd: diaParams.current?.args.dgnd,
    //     dgsyh: v
    // });
    // if (res.success) return notify('该索引号重复', 'warning', 2000);


    const regExpFunc = (rule: any, value: string) => {
        const reg = /^(?!.*\.\w+$).*/;
        if (value && !reg.test(value)) {
            return Promise.reject('名称不能有.后缀！');
        }
        return Promise.resolve();
    };

    // const handleIdValidator = async (_, value: any) => {
    //     // setValidateHelp('ID校验中......');
    //     setFormSyh({
    //         validateStatus: false,
    //         validateHelp: '校验中...'
    //     })
    //     // step1. 非空校验
    //     if (value === undefined || !value.trim()) {
    //         setFormSyh({
    //             validateStatus: false,
    //             validateHelp: '校验中...'
    //         })
    //         // setFormSyh({
    //         //     validateStatus:'error',
    //         //     validateHelp: '校验中...'
    //         // })
    //         throw new Error();
    //     }

    //     // step2. 开始校验
    //     setFormSyh({
    //         validateStatus: 'validating',
    //         validateHelp: '校验中...'
    //     })
    //     try {
    //         const res = await api(value); // todo 后端校验请求
    //         if (res) {
    //             setValidateStatus('success');
    //             setValidateHelp(undefined);
    //             return res;
    //         }
    //     } catch (e: any) {
    //         setValidateStatus('error');
    //         setValidateHelp('无效的厂商ID！');
    //         throw new Error(e); // ↑ 错误信息会显示手动设置的 help（不会显示 Error 中的值）
    //     }
    // }






    const onOk = async () => {

        const values = await formUseRef.validateFields()
        // console.log(values, '@@@');

        if (InputObjRef.current.pupopType === 'dg') {
            if (values?.fileName) {
                const res = await queryDgmc({
                    dbname: InputObjRef.current.dbname,
                    dgnd: InputObjRef.current.dgnd,
                    dgmc: values?.fileName
                });
                if (res.success) {
                    notify('该底稿名称号重复', 'error', 2000);
                    return;
                };
            }
            if (values?.fileSyh) {
                const res = await queryDgsyh({
                    dbname: InputObjRef.current.dbname,
                    dgnd: InputObjRef.current.dgnd,
                    dgsyh: values?.fileSyh
                });
                if (res.success) {
                    notify('该索引号重复', 'error', 2000);
                    return;
                };
            }
        } else {
            if (values?.fileName) {
                const res = await queryfjName({
                    dbname: InputObjRef.current.dbname,
                    fjName: values?.fileName
                });
                if (res.success) {
                    notify('该附件名称号重复', 'error', 2000);
                    return;
                };
            }
        }
        setVisible(false);
        InputFunRef.current?.okCallback({ ...values, itemKey: InputObjRef.current.itemKey });
        return;
    }

    const onCancel = () => {
        setVisible(false)
    }
    return (
        <>
            <Popup
                ref={popupRef}
                visible={visible}
                title='编辑'
                {...props}
                width={500}
                height={240}
                // dragOutsideBoundary={true}
                // resizeEnabled={true}
                onHiding={() => setVisible(false)}
                toolbarItems={[

                    {
                        widget: 'dxButton',
                        toolbar: 'bottom',
                        location: 'after',
                        options: {
                            text: intl('pub.cancel', '否'),
                            onClick: () => onCancel()
                        },
                    },
                    {
                        widget: 'dxButton',
                        toolbar: 'bottom',
                        location: 'after',
                        options: {
                            text: intl('pub.ok', '是'),
                            type: 'default',
                            onClick: () => onOk()
                        },
                    },

                ]}
            >
                <Form
                    layout="horizontal"
                    labelCol={{ span: 5 }}
                    form={formUseRef}
                    name="form_in_modal"
                // initialValues={{ modifier: 'public' }}
                // clearOnDestroy
                // onFinish={(values) => {
                //     console.log(values, '@@@@@');
                // }}
                >
                    {openForm.itemSyh && <Form.Item
                        name="fileSyh"
                        label="文件索引号"
                        rules={[
                            { required: true, message: '请输入索引号！' },
                        ]}
                    // hasFeedback
                    // validateTrigger="onBlur" // 输入完成, 失去焦点后开始校验
                    // validateStatus={validateStatus}
                    // help={validateHelp}
                    // rules={[
                    //     // { required: true },
                    //     { validator: handleIdValidator },
                    // ]}
                    >
                        <Input />
                    </Form.Item>}
                    {openForm.itemName && <Form.Item name="fileName" label="文件名称"
                        rules={[
                            { required: true, message: '请输入文件名称!' },
                            { validator: regExpFunc }
                        ]}
                    >
                        <Input />
                    </Form.Item>}
                </Form>
            </Popup >

        </>
    );
});

export default ErrorEditPupop;
